interval(1000)
map
counter
,可以記錄著每秒-1的結果
: scan
counter=0
時,不再傳送任何數值: filter
import { interval, map, scan, filter } from 'rxjs';
// final countdown
const finalCountdown$ = interval(1000).pipe(
map((val) => 1),
scan((accum, current) => accum - current, 6),
filter((val) => val >= 0)
);
// show on console
finalCountdown$.subscribe(console.log);
// 每秒印出
// 5
// 4
// 3
// 2
// 1
import { interval, map, scan, filter } from 'rxjs';
// get element
const countdown = document.getElementById('countdown');
const message = document.getElementById('message');
// final countdown
const finalCountdown$ = interval(1000).pipe(
map((val) => 1),
scan((accum, current) => accum - current, 6),
filter((val) => val >= 0)
);
// modify HTML
finalCountdown$.subscribe((val) => {
countdown.innerHTML = `${val}`;
if (!val) message.innerHTML = 'HAPPY NEW YEAR!!';
});
RxJS Operator
interval
map
filter
RxJS
就是將這些operator
的組合多加練習使用,時間一久,大腦建立習慣,你就能輕送駕馭它囉